package com.macro.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.dao.SmsFlashPromotionProductRelationDao;
import com.macro.mall.dao.SmsFlashPromotionSkuRelationDao;
import com.macro.mall.dto.SmsFlashPromotionProduct;
import com.macro.mall.mapper.SmsFlashPromotionMapper;
import com.macro.mall.mapper.SmsFlashPromotionProductRelationMapper;
import com.macro.mall.mapper.SmsFlashPromotionSessionMapper;
import com.macro.mall.model.*;
import com.macro.mall.service.SmsFlashPromotionProductRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 限时购商品关联管理Service实现类
 * Created by macro on 2018/11/16.
 */
@Service
@Slf4j
public class SmsFlashPromotionProductRelationServiceImpl implements SmsFlashPromotionProductRelationService {
    @Autowired
    private SmsFlashPromotionProductRelationMapper relationMapper;
    @Autowired
    private SmsFlashPromotionProductRelationDao relationDao;
    @Autowired
    private SmsFlashPromotionSessionMapper smsFlashPromotionSessionMapper;
    @Autowired
    private SmsFlashPromotionSkuRelationDao smsFlashPromotionSkuRelationDao;
    @Autowired
    private SmsFlashPromotionMapper smsFlashPromotionMapper;

    @Override
    public int create(List<SmsFlashPromotionProductRelation> relationList) {
        for (SmsFlashPromotionProductRelation relation : relationList) {
            relationMapper.insert(relation);
        }
        return relationList.size();
    }

    @Override
    public void update(Long id, SmsFlashPromotionProductRelation relation) {
        relation.setId(id);
        Date date = new Date();
        //通过id查询sms_flash_promotion_product_relation得到的活动及场次信息
       SmsFlashPromotionProductRelation relationList = relationMapper.selectById(relation.getId());
        //校验当前场次是否已经开始
        Long flashPromotionSessionId = relationList.getFlashPromotionSessionId();
        //通过id拿到场次时间信息
        SmsFlashPromotionSession smsFlashPromotionSession = smsFlashPromotionSessionMapper.selectByPrimaryKey(flashPromotionSessionId);
       //查找年月日
        SmsFlashPromotion smsFlashPromotion = smsFlashPromotionMapper.selectByPrimaryKey(relationList.getFlashPromotionId());
        //活动是否开启状态
        Integer status = smsFlashPromotionSession.getStatus();
        //判断状态是否开启 1就是开启
        if (status==1) {
            //开始结束时间（时分秒）
            Date startTime = smsFlashPromotionSession.getStartTime();
            Date endTime = smsFlashPromotionSession.getEndTime();
            // 获取当前时间
            long time = date.getTime();
            // 获取年月日（年月日）
            Date startDate = smsFlashPromotion.getStartDate();
            Date endDate = smsFlashPromotion.getEndDate();
            //判断是否在时间范围之内，看看是否还可以继续购买
            boolean dateTimeBetween = TimeUtils.isDateTimeBetween(date, startTime, endTime);
            if (dateTimeBetween) {
                //拿到sku列表
                List<PmsSkuStock> pmsSkuStocks = relationList.getSmsFlashPromotionSkuRelationsList();
                //遍历sku列表
                for (PmsSkuStock pmsSkuStock : pmsSkuStocks) {
                    //根据relation的是亏的及第一步得到的活动id及场次id，作为组合条件，删除
                    relationMapper.batchDel(
                            relationList.getFlashPromotionId()
                            ,relationList.getFlashPromotionSessionId(),
                            pmsSkuStock.getId());
                }
                //遍历sku列表
                for (PmsSkuStock pmsSkuStock : pmsSkuStocks) {
                    //创建sku和那什么表
                    SmsFlashPromotionSkuRelation smsFlashPromotionSkuRelation = new SmsFlashPromotionSkuRelation();
                    //把这个查到的内容给他set进去那个sku什么表
                    smsFlashPromotionSkuRelation.setFlashPromotionId(relationList.getFlashPromotionId());
                    smsFlashPromotionSkuRelation.setFlashPromotionSessionId(relationList.getFlashPromotionSessionId());
                    smsFlashPromotionSkuRelation.setFlashPromotionCount(relationList.getFlashPromotionCount());
                    smsFlashPromotionSkuRelation.setFlashPromotionPrice(relationList.getFlashPromotionPrice());
                    smsFlashPromotionSkuRelation.setFlashPromotionLimit(relationList.getFlashPromotionLimit());
                    smsFlashPromotionSkuRelation.setSkuId(pmsSkuStock.getId());
                    //批量添加
                    relationMapper.batchAdd(smsFlashPromotionSkuRelation);
                }
            }else {
                log.error("还没开始呢，急个毛线");
            }
        }
    }


    //校验时间的方法
    public class TimeUtils {

        // 私有构造函数，防止实例化工具类
        private TimeUtils() {
            throw new UnsupportedOperationException("Cannot instantiate utility class");
        }

        // 判断一个日期时间是否在两个日期时间之间（包括开始时间，不包括结束时间）
        public static boolean isDateTimeBetween(Date dateTime, Date startTime, Date endTime) {
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTime);
            startCalendar.set(Calendar.MILLISECOND, 0); // 确保开始时间没有毫秒部分

            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endTime);
            // 注意：这里我们不设置毫秒为999，因为我们要确保不包括结束时间本身。
            // 直接使用dateTime.before(endCalendar.getTime())将排除结束时间。

            // 判断日期时间是否在开始日期时间和结束日期时间之间
            return !dateTime.before(startCalendar.getTime()) && dateTime.before(endCalendar.getTime());
        }

        // 判断当前日期时间是否在两个日期时间之间（包括开始时间，不包括结束时间）
        public static boolean isCurrentDateTimeBetween(Date startTime, Date endTime) {
            // 获取当前日期时间
            Date currentDateTime = new Date();
            // 调用另一个isDateTimeBetween方法来检查当前日期时间
            return isDateTimeBetween(currentDateTime, startTime, endTime);
        }
        // （可选）如果你还需要处理时间字符串，可以保留原来的解析和比较逻辑，
        // 或者将字符串解析为Date的逻辑封装在一个单独的方法中。
        // ...（例如，一个将字符串解析为Date的辅助方法）
    }



    @Override
    public int delete(Long id) {
        return relationMapper.deleteByPrimaryKey(id);
    }

    @Override
    public SmsFlashPromotionProductRelation getItem(Long id) {
        return relationMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SmsFlashPromotionProduct> list(Long flashPromotionId, Long flashPromotionSessionId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        return relationDao.getList(flashPromotionId,flashPromotionSessionId);
    }

    @Override
    public long getCount(Long flashPromotionId, Long flashPromotionSessionId) {
        SmsFlashPromotionProductRelationExample example = new SmsFlashPromotionProductRelationExample();
        example.createCriteria()
                .andFlashPromotionIdEqualTo(flashPromotionId)
                .andFlashPromotionSessionIdEqualTo(flashPromotionSessionId);
        return relationMapper.countByExample(example);
    }
}
